<template>
  <view class="container">
    <view class="form-card">
      <view class="form-header">
        <view class="form-title">快递登记</view>
        <view class="form-desc">登记后可在快递服务页查看并等待工作人员送达</view>
      </view>

      <view class="form-item">
        <view class="form-label">村小组 <text class="required">*</text></view>
        <picker class="form-picker" :value="groupIndex" :range="villageGroups" @change="onGroupChange">
          <view class="picker-text">{{ formData.villageGroup || '请选择村小组' }}</view>
        </picker>
      </view>

      <view class="form-item">
        <view class="form-label">快递人 <text class="required">*</text></view>
        <input class="form-input" v-model="formData.recipient" placeholder="请输入快递人姓名" />
      </view>

      <view class="form-item">
        <view class="form-label">联系方式 <text class="required">*</text></view>
        <input class="form-input" v-model="formData.contactPhone" placeholder="请输入手机号码" maxlength="20" />
      </view>

      <view class="form-item">
        <view class="form-label">取件码 <text class="required">*</text></view>
        <input class="form-input" v-model="formData.pickupCode" placeholder="请输入取件码" maxlength="20" />
      </view>

      <view class="form-item">
        <view class="form-label">备注</view>
        <textarea class="form-textarea" v-model="formData.remark" placeholder="可以补充快递品牌或其他说明" maxlength="120" />
        <view class="char-count">{{ formData.remark.length }}/120</view>
      </view>

      <button class="submit-btn" :disabled="!canSubmit" @tap="submitForm">
        {{ submitting ? '提交中...' : '提交登记' }}
      </button>
      <view class="tips-text">登记信息仅自己可见，送达情况请留意通知</view>
    </view>
  </view>
</template>

<script>
import { expressApi, commonApi } from '@/utils/api-simple.js'
import authService from '@/utils/auth.js'

export default {
  data() {
    return {
      villageGroups: [],
      groupIndex: -1,
      formData: {
        villageGroup: '',
        recipient: '',
        contactPhone: '',
        pickupCode: '',
        remark: ''
      },
      submitting: false
    }
  },
  computed: {
    canSubmit() {
      return this.formData.villageGroup &&
        this.formData.recipient &&
        this.formData.contactPhone &&
        this.formData.pickupCode &&
        !this.submitting
    }
  },
  onLoad() {
    this.checkAuthAndLoad()
  },
  methods: {
    async checkAuthAndLoad() {
      if (!authService.isLoggedIn()) {
        uni.showToast({ title: '请先登录', icon: 'none' })
        setTimeout(() => {
          uni.redirectTo({ url: '/pages/login/login?from=/pages/express-form/express-form' })
        }, 1200)
        return
      }
      const userInfo = authService.getUserInfo()
      if (userInfo && !this.formData.recipient) {
        this.formData.recipient = userInfo.wechatNickname || userInfo.nickName || userInfo.userName || ''
      }
      await this.loadVillageGroups()
    },
    async loadVillageGroups() {
      try {
        const groups = await commonApi.getVillageGroups()
        if (Array.isArray(groups) && groups.length > 0) {
          this.villageGroups = groups
        } else {
          this.villageGroups = ['刘家湾组', '陈家湾组', '杜家冲组', '五坝组', '长房组', '大坪子组']
        }
        if (this.formData.villageGroup) {
          const idx = this.villageGroups.indexOf(this.formData.villageGroup)
          if (idx >= 0) {
            this.groupIndex = idx
          }
        }
      } catch (error) {
        console.warn('加载村小组失败，使用默认值', error)
        this.villageGroups = ['刘家湾组', '陈家湾组', '杜家冲组', '五坝组', '长房组', '大坪子组']
      }
    },
    onGroupChange(e) {
      const index = e.detail.value
      this.groupIndex = index
      this.formData.villageGroup = this.villageGroups[index]
    },
    async submitForm() {
      if (!this.canSubmit) {
        uni.showToast({ title: '请完善信息后再提交', icon: 'none' })
        return
      }
      this.submitting = true
      uni.showLoading({ title: '提交中...' })
      try {
        const response = await expressApi.submitExpress({
          villageGroup: this.formData.villageGroup,
          recipient: this.formData.recipient,
          contactPhone: this.formData.contactPhone,
          pickupCode: this.formData.pickupCode,
          remark: this.formData.remark
        })
        if (response.code === 200) {
          uni.hideLoading()
          const serial = response.serial || (response.data && response.data.serial) || '未知编号'
          uni.showModal({
            title: '登记成功',
            content: `登记编号：${serial}，工作人员送达后将更新状态。`,
            showCancel: false,
            success: () => {
              uni.$emit('refreshExpressList')
              uni.navigateBack()
            }
          })
        } else {
          throw new Error(response.msg || '提交失败')
        }
      } catch (error) {
        console.error('快递登记失败', error)
        uni.hideLoading()
        uni.showToast({
          title: error.message || '提交失败，请重试',
          icon: 'none'
        })
      } finally {
        this.submitting = false
      }
    }
  }
}
</script>

<style scoped>
.container {
  min-height: 100vh;
  padding: 24rpx;
  background-color: #f5f6fa;
  box-sizing: border-box;
}

.form-card {
  background-color: #fff;
  border-radius: 24rpx;
  padding: 32rpx;
  box-shadow: 0 12rpx 30rpx rgba(0, 0, 0, 0.04);
}

.form-header {
  margin-bottom: 30rpx;
}

.form-title {
  font-size: 38rpx;
  font-weight: bold;
  color: #333;
}

.form-desc {
  margin-top: 8rpx;
  font-size: 26rpx;
  color: #888;
}

.form-item {
  margin-bottom: 26rpx;
}

.form-label {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 12rpx;
}

.required {
  color: #f56c6c;
}

.form-input,
.form-picker {
  width: 100%;
  min-height: 88rpx;
  border-radius: 16rpx;
  border: 1rpx solid #e5e6eb;
  padding: 0 24rpx;
  box-sizing: border-box;
  font-size: 28rpx;
  color: #333;
  background-color: #fdfdfd;
  display: flex;
  align-items: center;
}

.picker-text {
  color: #333;
}

.form-textarea {
  width: 100%;
  min-height: 180rpx;
  border-radius: 16rpx;
  border: 1rpx solid #e5e6eb;
  padding: 16rpx 24rpx;
  font-size: 28rpx;
  color: #333;
  box-sizing: border-box;
}

.char-count {
  margin-top: 8rpx;
  font-size: 24rpx;
  color: #999;
  text-align: right;
}

.submit-btn {
  width: 100%;
  background: linear-gradient(135deg, #07c160, #06a356);
  color: #fff;
  border: none;
  border-radius: 24rpx;
  padding: 26rpx 0;
  font-size: 32rpx;
  margin-top: 20rpx;
}

.submit-btn:disabled {
  background: #c4dad1;
  color: #fff;
}

.tips-text {
  margin-top: 16rpx;
  text-align: center;
  font-size: 24rpx;
  color: #999;
}
</style>

